<template>
  <div class="progress-container">
    <div class="page-header">
      <h2>学习进度总览</h2>
      <div class="header-actions">
        <el-select v-model="timeRange" placeholder="时间范围" class="filter-select" @change="handleTimeRangeChange">
          <el-option label="本周" value="week" />
          <el-option label="本月" value="month" />
          <el-option label="全部" value="all" />
        </el-select>
      </div>
    </div>

    <!-- 学习进度一览部分 -->
    <div class="section-wrapper">
      <div class="progress-grid">
        <!-- 总体进度卡片 -->
        <el-card class="progress-card overall-progress" v-loading="loading.overall">
          <div class="card-header">
            <h3>总体学习进度</h3>
            <el-tag type="success">进行中</el-tag>
          </div>
          <div class="progress-circle">
            <el-progress 
              type="dashboard" 
              :percentage="averageProgress" 
              :color="progressColors"
            />
          </div>
          <div class="progress-stats">
            <div class="stat-item">
              <span class="label">已学习天数</span>
              <span class="value">{{ stats.studyDays }}</span>
            </div>
            <div class="stat-item">
              <span class="label">注册天数</span>
              <span class="value">{{ stats.registerDays }}</span>
            </div>
            <div class="stat-item">
              <span class="label">完成题目</span>
              <span class="value">{{ stats.completedQuestions }}</span>
            </div>
            <div class="stat-item">
              <span class="label">正确率</span>
              <span class="value">{{ stats.accuracy }}%</span>
            </div>
          </div>
        </el-card>

        <!-- 每日学习时长图表 -->
        <el-card class="progress-card chart-card" v-loading="loading.chart">
          <div class="card-header">
            <h3>每日学习时长</h3>
          </div>
          <div ref="studyTimeChart" class="chart-container"></div>
        </el-card>

        <!-- 知识点掌握情况 -->
        <el-card class="progress-card knowledge-card" v-loading="loading.knowledge">
          <div class="card-header">
            <h3>薄弱知识点</h3>
            <el-select v-model="selectedCourse" placeholder="选择课程" @change="handleCourseChange" size="small">
              <el-option label="全部课程" :value="0" />
              <el-option v-for="course in courseList" :key="course.courseId" :label="course.courseName" :value="course.courseId" />
            </el-select>
          </div>
          <div class="knowledge-list">
            <div v-if="filteredKnowledgePoints.length === 0" class="empty-state">
              暂无薄弱知识点数据
            </div>
            <div v-else>
              <div v-for="item in filteredKnowledgePoints" :key="item.pointId || item.subject" class="knowledge-item">
                <div class="knowledge-info">
                  <span class="name">{{ item.pointName || item.subject }}</span>
                  <span class="progress-text">错误次数: {{ item.errorCount || 0 }}</span>
                </div>
                <el-progress 
                  :percentage="calculateProgress(item)" 
                  :color="getProgressColor(calculateProgress(item))"
                />
                <div class="progress-explanation">
                  掌握度: {{ calculateProgress(item) }}% (错误次数越多，掌握度越低)
                </div>
              </div>
            </div>
            <div class="calculation-explanation">
              <el-alert
                title="进度条计算说明"
                type="info"
                :closable="false"
                show-icon
              >
                <div class="explanation-content">
                  <p><strong>掌握度计算方式：</strong></p>
                  <ul>
                    <li>错误次数为0：掌握度100%</li>
                    <li>错误次数1-10：掌握度90%-99%</li>
                    <li>错误次数11-30：掌握度70%-89%</li>
                    <li>错误次数31-50：掌握度50%-69%</li>
                    <li>错误次数51-100：掌握度0%-49%</li>
                    <li>错误次数>100：掌握度0%</li>
                  </ul>
                  <p>建议重点复习掌握度低于70%的知识点</p>
                </div>
              </el-alert>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 新增：学习笔记卡片 -->
    <el-card class="notes-card">
      <template #header>
        <div class="card-header">
          <h3>学习笔记</h3>
          <el-button type="primary" @click="showNoteDialog">添加笔记</el-button>
        </div>
      </template>
      <div class="notes-list">
        <div v-for="note in notes" :key="note.noteId" class="note-item">
          <div class="note-header">
            <div class="note-title-container">
              <span class="note-title">{{ note.questionTitle }}</span>
              <div class="note-tags">
                <el-tag v-if="isWrongQuestion(note.questionId)" size="small" type="danger">错题</el-tag>
                <el-tag v-if="isFavoriteQuestion(note.questionId)" size="small" type="warning">收藏</el-tag>
                <el-tag size="small" :type="note.isPublic ? 'success' : 'info'">
                  {{ note.isPublic ? '公开' : '私密' }}
                </el-tag>
              </div>
            </div>
          </div>
          <div class="note-content">{{ note.content }}</div>
          <div class="note-footer">
            <span class="note-time">{{ formatDate(note.createTime) }}</span>
            <div class="note-actions">
              <el-button link @click="editNote(note)">编辑</el-button>
              <el-button link @click="shareNote(note)">分享</el-button>
              <el-popconfirm
                title="确定要删除这条笔记吗？"
                @confirm="deleteNote(note)"
                confirm-button-text="确定"
                cancel-button-text="取消"
              >
                <template #reference>
                  <el-button link class="delete-btn">删除</el-button>
                </template>
              </el-popconfirm>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 添加笔记对话框 -->
    <el-dialog
      v-model="noteDialog.visible"
      :title="noteDialog.isEdit ? '编辑笔记' : '添加笔记'"
      width="50%"
    >
      <el-form :model="noteForm" label-width="80px">
        <el-form-item label="题目来源">
          <el-radio-group v-model="questionSourceType" @change="handleSourceChange">
            <el-radio :value="'wrong'">错题本</el-radio>
            <el-radio :value="'favorite'">收藏夹</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="题目">
          <el-select 
            v-model="noteForm.questionId" 
            placeholder="选择题目" 
            style="width: 100%"
            filterable
            :filter-method="filterQuestions"
          >
            <el-option
              v-for="question in filteredQuestionList"
              :key="question.questionId"
              :label="question.content || question.questionContent"
              :value="question.questionId"
            >
              <div class="question-option">
                <div class="question-content">
                  {{ question.content || question.questionContent }}
                  <el-tag v-if="question.isWrong" size="small" type="danger" style="margin-left: 5px;">错题</el-tag>
                  <el-tag v-if="question.isFavorite" size="small" type="warning" style="margin-left: 5px;">收藏</el-tag>
                </div>
                <div class="question-info">
                  <el-tag size="small" :type="getQuestionTypeTag(question.questionType)">
                    {{ getQuestionTypeText(question.questionType) }}
                  </el-tag>
                  <el-tag size="small" :type="getDifficultyTag(question.difficulty)">
                    {{ getDifficultyText(question.difficulty) }}
                  </el-tag>
                </div>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="笔记内容">
          <el-input
            v-model="noteForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入笔记内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="noteDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="handleNoteSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分享笔记对话框 -->
    <el-dialog
      v-model="shareDialog.visible"
      title="分享笔记"
      width="30%"
    >
      <el-form :model="shareForm" label-width="80px">
        <el-form-item label="分享给">
          <el-select v-model="shareForm.targetUserId" placeholder="选择用户" style="width: 100%">
            <el-option
              v-for="user in users"
              :key="user.userId"
              :label="user.username"
              :value="user.userId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="shareDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="handleShareSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, onUnmounted, watch } from 'vue'
import * as echarts from 'echarts'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '../../../store/UserStore'
import { useRouter } from 'vue-router'

const router = useRouter()
const userStore = useUserStore()
const userInfo = computed(() => userStore.userInfo)

const userId = ref(1)
const timeRange = ref('week')
const overallProgress = ref(0)
const progressColors = [
  { color: '#f56c6c', percentage: 20 },
  { color: '#e6a23c', percentage: 40 },
  { color: '#5cb87a', percentage: 60 },
  { color: '#1989fa', percentage: 80 },
  { color: '#6f7ad3', percentage: 100 }
]

const stats = ref({
  studyDays: 0,
  registerDays: 0,
  completedQuestions: 0,
  accuracy: 0
})

const knowledgePoints = ref([])
const studyTimeChart = ref(null)
let chartInstance = null // 添加图表实例变量
const notes = ref([])

// 1. 课程进度数据
const courseProgressList = ref([])

// 加载状态
const loading = ref({
  overall: false,
  chart: false,
  knowledge: false
})

// 笔记对话框状态
const noteDialog = ref({
  visible: false,
  isEdit: false
})

// 题目来源选择
const questionSourceType = ref('wrong') // 默认为错题本
// 记录已加载的题目，避免重复加载
const loadedQuestions = ref({
  wrong: [],
  favorite: []
})

// 笔记表单数据
const noteForm = ref({
  noteId: null,
  questionId: null,
  content: ''
})

// 分享对话框状态
const shareDialog = ref({
  visible: false
})

// 分享表单数据
const shareForm = ref({
  noteId: null,
  targetUserId: null
})

// 题目列表
const questions = ref([])
// 用户列表
const users = ref([])
// 错题列表
const wrongQuestions = ref([])
// 收藏题目列表
const favoriteQuestions = ref([])

// 在 script setup 部分添加以下内容
const filteredQuestionList = ref([])
const questionSearchText = ref('')

// 获取题目列表
const fetchQuestions = async () => {
  try {
    const userId = userStore.getUserInfo.userId
    const sourceType = questionSourceType.value
    
    // 如果已经加载过该类型的题目，直接使用缓存
    if (loadedQuestions.value[sourceType].length > 0) {
      questions.value = loadedQuestions.value[sourceType]
      filteredQuestionList.value = getFilteredQuestions()
      return
    }
    
    // 显示加载状态
    ElMessage.info('正在加载题目...')
    
    // 根据选择的来源获取题目
    if (sourceType === 'wrong') {
      // 直接获取错题本中的题目
      const response = await axios.get(`http://localhost:8080/wrongquestions/query`, {
        params: { userId: userId }
      })
      if (response.data && response.data.records) {
        // 处理返回的错题数据，确保每个题目都有 isWrong 标记
        const wrongQuestionsList = response.data.records.map(item => ({
          ...item,
          questionId: item.questionId,
          content: item.questionContent,
          isWrong: true,
          isFavorite: false // 默认不是收藏，后续可以检查
        }))
        questions.value = wrongQuestionsList
        loadedQuestions.value.wrong = wrongQuestionsList // 缓存结果
      } else {
        questions.value = []
      }
    } else if (sourceType === 'favorite') {
      // 直接获取收藏夹中的题目
      const response = await axios.get(`http://localhost:8080/favorites/query`, {
        params: { userId: userId }
      })
      if (response.data && Array.isArray(response.data)) {
        // 处理返回的收藏题目数据，确保每个题目都有 isFavorite 标记
        const favoriteQuestionsList = response.data.map(item => ({
          ...item,
          questionId: item.question_id,
          content: item.question_content,
          isWrong: false, // 默认不是错题，后续可以检查
          isFavorite: true
        }))
        questions.value = favoriteQuestionsList
        loadedQuestions.value.favorite = favoriteQuestionsList // 缓存结果
      } else {
        questions.value = []
      }
    }
    
    // 更新过滤后的题目列表
    filteredQuestionList.value = getFilteredQuestions()
  } catch (error) {
    console.error('获取题目列表失败:', error)
    ElMessage.error('获取题目列表失败')
    questions.value = []
    filteredQuestionList.value = []
  }
}

// 处理题目来源变化 - 使用防抖
const handleSourceChange = debounce(() => {
  // 重置题目选择
  noteForm.value.questionId = null
  // 重新获取对应来源的题目
  fetchQuestions()
}, 300)

// 防抖函数
function debounce(fn, delay = 300) {
  let timer = null
  return function() {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, arguments)
    }, delay)
  }
}

// 根据来源类型获取过滤后的题目
const getFilteredQuestions = () => {
  switch (questionSourceType.value) {
    case 'wrong':
      return questions.value.filter(q => q.isWrong)
    case 'favorite':
      return questions.value.filter(q => q.isFavorite)
    default:
      return questions.value
  }
}

// 过滤题目列表 - 使用防抖
const filterQuestions = debounce((query) => {
  questionSearchText.value = query
  if (query) {
    // 本地过滤，避免重复请求
    filteredQuestionList.value = getFilteredQuestions().filter(question => {
      // 根据题目来源不同，字段名可能不同
      const content = question.content || question.questionContent || ''
      return content.toLowerCase().includes(query.toLowerCase())
    })
  } else {
    filteredQuestionList.value = getFilteredQuestions()
  }
}, 300)

// 获取题目类型标签样式
const getQuestionTypeTag = (type) => {
  const typeMap = {
    'CS01': 'primary',
    'CS02': 'success',
    'CS03': 'warning',
    'CS04': 'info'
  }
  return typeMap[type] || 'info'
}

// 获取题目类型文本
const getQuestionTypeText = (type) => {
  const typeMap = {
    'CS01': '单选题',
    'CS02': '多选题',
    'CS03': '填空题',
    'CS04': '简答题'
  }
  return typeMap[type] || '未知类型'
}

// 获取难度标签样式
const getDifficultyTag = (difficulty) => {
  const difficultyMap = {
    1: 'success',
    2: 'info',
    3: 'warning',
    4: 'danger',
    5: 'danger'
  }
  return difficultyMap[difficulty] || 'info'
}

// 获取难度文本
const getDifficultyText = (difficulty) => {
  const difficultyMap = {
    1: '基础',
    2: '简单',
    3: '中等',
    4: '困难',
    5: '极难'
  }
  return difficultyMap[difficulty] || '未知难度'
}

// 获取总体进度
const fetchOverallProgress = async () => {
  loading.value.overall = true
  try {
    // 1. 获取用户分析数据 - 使用auto-analyze接口
    const analysisResponse = await axios.get(`http://localhost:8080/useranalysis/auto-analyze`, {
      params: {
        userId: userId.value
        // 不提供courseId参数，获取所有课程的汇总数据
      }
    })
    console.log('用户分析数据响应:', analysisResponse.data)

    // 2. 获取练习记录
    const practiceResponse = await axios.get(`http://localhost:8080/userPractices/user/${userId.value}`)
    const practiceData = practiceResponse.data || []
    
    // 3. 获取考试记录
    const examResponse = await axios.get(`http://localhost:8080/userexams/byUser/${userId.value}`)
    const examData = examResponse.data || []

    // 4. 获取用户信息(用于计算注册天数)
    const userResponse = await axios.get(`http://localhost:8080/user/user_find/${userId.value}`)
    const userData = userResponse.data || {}

    // 计算学习天数
    const studyDays = new Set()
    
    // 添加练习记录的天数
    practiceData.forEach(practice => {
      if (practice.startTime) {
        const date = new Date(practice.startTime).toISOString().split('T')[0]
        studyDays.add(date)
      }
    })
    
    // 添加考试记录的天数
    examData.forEach(exam => {
      if (exam.examTime) {
        const date = new Date(exam.examTime).toISOString().split('T')[0]
        studyDays.add(date)
      }
    })

    // 计算注册天数
    let registerDays = 0
    if (userData.registerTime) {
      const registerDate = new Date(userData.registerTime)
      const today = new Date()
      registerDays = Math.floor((today - registerDate) / (1000 * 60 * 60 * 24)) + 1
    }

    // 从用户分析数据中获取完成题目数和正确率
    if (analysisResponse.data) {
      // 使用auto-analyze接口返回的数据结构
      const analysisData = analysisResponse.data;
      console.log('分析数据:', analysisData)
      
      // 更新统计数据
      stats.value = {
        studyDays: studyDays.size,
        registerDays: registerDays,
        completedQuestions: analysisData.totalQuestions || 0,
        accuracy: analysisData.averageAccuracyRate ? Math.round(analysisData.averageAccuracyRate * 100) : 0
      }

      // 设置总体进度
      overallProgress.value = analysisData.progress || 0
    } else {
      console.log('未找到用户分析数据，使用默认值')
      stats.value = {
        studyDays: studyDays.size,
        registerDays: registerDays,
        completedQuestions: 0,
        accuracy: 0
      }
      overallProgress.value = 0
    }

  } catch (error) {
    console.error('获取总体进度失败:', error)
    console.log('错误详情:', {
      message: error.message,
      response: error.response?.data,
      status: error.response?.status,
      config: error.config,
      url: error.config?.url,
      method: error.config?.method,
      params: error.config?.params
    })
    ElMessage.error('获取总体进度失败')
    // 设置默认值
    stats.value = {
      studyDays: 0,
      registerDays: 0,
      completedQuestions: 0,
      accuracy: 0
    }
    overallProgress.value = 0
  } finally {
    loading.value.overall = false
  }
}

// 在 script setup 部分添加以下内容
const courseList = ref([
  { courseId: 1, courseName: "数据结构" },
  { courseId: 2, courseName: "操作系统" },
  { courseId: 3, courseName: "计算机组成原理" },
  { courseId: 4, courseName: "计算机网络" }
])
const selectedCourse = ref(0) // 0表示全部课程
const allKnowledgePoints = ref([]) // 存储所有课程的薄弱知识点

// 筛选后的知识点
const filteredKnowledgePoints = computed(() => {
  if (selectedCourse.value === 0) {
    return allKnowledgePoints.value
  } else {
    return allKnowledgePoints.value.filter(point => point.courseId === selectedCourse.value)
  }
})

// 处理课程选择变化
const handleCourseChange = () => {
  console.log('选择的课程ID:', selectedCourse.value)
}

// 获取知识点掌握情况
const fetchKnowledgePoints = async () => {
  loading.value.knowledge = true
  try {
    // 获取所有课程的薄弱知识点
    const allPoints = []
    
    // 1. 调用auto-analyze接口获取所有课程的分析数据
    try {
      // 不传courseId参数，获取所有课程的汇总数据
      const analysisResponse = await axios.get(`http://localhost:8080/useranalysis/auto-analyze`, {
        params: { 
          userId: userId.value
        }
      })
      
      console.log('所有课程分析数据:', analysisResponse.data)
      
      // 2. 解析weakPoints字段
      if (analysisResponse.data && analysisResponse.data.weakPoints) {
        let weakPoints
        
        try {
          // 解析weakPoints字段（应该是JSON字符串）
          weakPoints = typeof analysisResponse.data.weakPoints === 'string'
            ? JSON.parse(analysisResponse.data.weakPoints)
            : analysisResponse.data.weakPoints
            
          console.log('解析后的薄弱知识点:', weakPoints)
          
          // 3. 如果是数组，直接使用
          if (Array.isArray(weakPoints)) {
            // 为每个知识点添加课程信息
            weakPoints.forEach(point => {
              // 根据知识点名称判断所属课程
              if (point.pointName.includes('数据结构') || point.pointName.includes('线性表') || point.pointName.includes('绪论')) {
                point.courseId = 1
                point.courseName = '数据结构'
              } else if (point.pointName.includes('进程') || point.pointName.includes('内存') || point.pointName.includes('操作系统')) {
                point.courseId = 2
                point.courseName = '操作系统'
              } else if (point.pointName.includes('计算机系统') || point.pointName.includes('组成原理')) {
                point.courseId = 3
                point.courseName = '计算机组成原理'
              } else if (point.pointName.includes('网络') || point.pointName.includes('协议') || point.pointName.includes('数据链路')) {
                point.courseId = 4
                point.courseName = '计算机网络'
              } else {
                // 默认分配
                const courseId = point.pointId % 4 + 1
                point.courseId = courseId
                point.courseName = courseList.value.find(c => c.courseId === courseId)?.courseName || '未知课程'
              }
              
              // 根据errorCount计算正确率
              const errorCount = point.errorCount || 0
              point.accuracy = Math.max(0, Math.min(1, 1 - errorCount / 100))
            })
            
            allPoints.push(...weakPoints)
          }
        } catch (e) {
          console.error('解析weakPoints失败:', e)
        }
      }
    } catch (error) {
      console.error('获取分析数据失败:', error)
    }
    
    console.log('处理后的薄弱知识点:', allPoints)
    
    // 4. 如果没有找到薄弱知识点，添加模拟数据
    if (allPoints.length === 0) {
      console.log('未找到薄弱知识点，添加模拟数据')
      allPoints.push(
        {
          pointId: 39,
          pointName: "第2章 进程与线程 - 2.1 进程与线程",
          errorCount: 53,
          courseId: 2,
          courseName: "操作系统",
          accuracy: 0.45
        },
        {
          pointId: 5,
          pointName: "第1章 绪论 - 1.1 数据结构的基本概念",
          errorCount: 4,
          courseId: 1,
          courseName: "数据结构",
          accuracy: 0.96
        },
        {
          pointId: 7,
          pointName: "第2章 线性表 - 2.1 线性表的定义和基本操作",
          errorCount: 4,
          courseId: 1,
          courseName: "数据结构",
          accuracy: 0.96
        }
      )
    }
    
    // 5. 按错误次数降序排序
    allPoints.sort((a, b) => b.errorCount - a.errorCount)
    
    // 6. 更新所有知识点
    allKnowledgePoints.value = allPoints
  } catch (error) {
    console.error('获取薄弱知识点失败:', error)
    console.error('错误详情:', {
      message: error.message,
      response: error.response?.data,
      status: error.response?.status,
      config: error.config
    })
    ElMessage.error('获取薄弱知识点失败')
    
    // 出错时添加模拟数据
    allKnowledgePoints.value = [
      {
        pointId: 39,
        pointName: "第2章 进程与线程 - 2.1 进程与线程",
        errorCount: 53,
        courseId: 2,
        courseName: "操作系统",
        accuracy: 0.45
      }
    ]
  } finally {
    loading.value.knowledge = false
  }
}

// 计算进度（根据错误次数和正确率计算掌握程度）
const calculateProgress = (item) => {
  if (item.progress !== undefined) {
    return item.progress
  }
  
  // 如果有正确率数据，优先使用正确率
  if (item.accuracy !== undefined) {
    return Math.round(item.accuracy * 100)
  }
  
  // 根据错误次数反推掌握程度
  const errorCount = item.errorCount || 0
  if (errorCount <= 0) return 100
  if (errorCount >= 100) return 0
  
  // 简单的反比例关系：100 - errorCount（最低为0，最高为100）
  return Math.max(0, Math.min(100, 100 - errorCount))
}

// 初始化学习时长图表
const initStudyTimeChart = async () => {
  loading.value.chart = true
  try {
    // 如果已存在图表实例,先销毁
    if (chartInstance) {
      chartInstance.dispose()
    }

    const response = await axios.get(`/userPractices/user/${userId.value}`)
    const data = processDailyStudyTime(response.data)
    
    // 确保DOM元素存在
    if (!studyTimeChart.value) {
      console.error('图表容器不存在')
      return
    }

    // 创建新的图表实例
    chartInstance = echarts.init(studyTimeChart.value)
    const option = {
      tooltip: { 
        trigger: 'axis',
        formatter: function(params) {
          const value = params[0].value
          return `${params[0].axisValue}<br/>${params[0].seriesName}: ${value}分钟`
        }
      },
      xAxis: { 
        type: 'category', 
        data: data.dates 
      },
      yAxis: { 
        type: 'value', 
        name: '学习时长(分钟)' 
      },
      series: [{
        name: '学习时长',
        type: 'line',
        smooth: true,
        data: data.durations,
        areaStyle: { opacity: 0.3 },
        lineStyle: { width: 3 },
        itemStyle: { borderWidth: 2 }
      }]
    }
    chartInstance.setOption(option)

    // 添加窗口大小变化时的自适应
    window.addEventListener('resize', () => {
      chartInstance && chartInstance.resize()
    })
  } catch (error) {
    console.error('初始化学习时长图表失败:', error)
    ElMessage.error('初始化学习时长图表失败')
  } finally {
    loading.value.chart = false
  }
}

// 处理每日学习时长数据
const processDailyStudyTime = (data) => {
  const dateMap = new Map()
  const today = new Date()
  const days = timeRange.value === 'week' ? 7 : timeRange.value === 'month' ? 30 : 365
  
  // 初始化日期
  for (let i = 0; i < days; i++) {
    const date = new Date(today)
    date.setDate(date.getDate() - i)
    const dateStr = date.toISOString().split('T')[0]
    dateMap.set(dateStr, 0)
  }
  
  // 统计每日学习时长(分钟)
  data.forEach(item => {
    const date = new Date(item.startTime).toISOString().split('T')[0]
    if (dateMap.has(date)) {
      // 将秒转换为分钟
      dateMap.set(date, dateMap.get(date) + Math.round((item.duration || 0) / 60))
    }
  })
  
  return {
    dates: Array.from(dateMap.keys()).reverse(),
    durations: Array.from(dateMap.values()).reverse()
  }
}

// 获取进度条颜色
const getProgressColor = (progress) => {
  if (progress >= 80) return '#67C23A'
  if (progress >= 60) return '#E6A23C'
  return '#F56C6C'
}

// 处理时间范围变化
const handleTimeRangeChange = () => {
  initStudyTimeChart()
}

// 获取学习笔记
const fetchNotes = async () => {
  try {
    // 确保用户ID存在
    const currentUserId = userStore.getUserInfo?.userId
    if (!currentUserId) {
      console.error('用户ID不存在')
      ElMessage.error('用户未登录')
      return
    }

    console.log('正在获取用户笔记，用户ID:', currentUserId)
    const response = await axios.get(`http://localhost:8080/api/notes/user/${currentUserId}`)
    
    console.log('笔记接口响应:', response)
    
    if (response.data && response.data.code === 200 && response.data.data) {
      notes.value = response.data.data
      console.log('成功获取笔记列表:', notes.value)
      
      // 获取错题和收藏信息
      await fetchWrongAndFavoriteStatus()
    } else {
      console.error('获取笔记失败，响应数据格式不正确:', response.data)
      ElMessage.error('获取学习笔记失败，数据格式异常')
    }
  } catch (error) {
    console.error('获取学习笔记失败:', error)
    console.error('错误详情:', {
      message: error.message,
      response: error.response?.data,
      status: error.response?.status,
      config: error.config
    })
    ElMessage.error(error.response?.data?.message || '获取学习笔记失败，请稍后重试')
  }
}

// 获取错题和收藏状态
const fetchWrongAndFavoriteStatus = async () => {
  try {
    const userId = userStore.getUserInfo.userId
    
    // 获取用户的错题
    const wrongResponse = await axios.get(`http://localhost:8080/wrongquestions/query`, {
      params: { userId: userId }
    })
    wrongQuestions.value = wrongResponse.data?.records || []
    
    // 获取用户的收藏题目
    const favoritesResponse = await axios.get(`http://localhost:8080/favorites/query`, {
      params: { userId: userId }
    })
    favoriteQuestions.value = favoritesResponse.data || []
  } catch (error) {
    console.error('获取错题和收藏状态失败:', error)
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
}

// 显示添加笔记对话框
const showNoteDialog = () => {
  noteDialog.value.isEdit = false
  questionSourceType.value = 'wrong' // 默认显示错题
  noteForm.value = {
    questionId: null,
    content: ''
  }
  noteDialog.value.visible = true
  
  // 如果已经加载过该类型的题目，直接使用缓存
  if (loadedQuestions.value[questionSourceType.value].length > 0) {
    questions.value = loadedQuestions.value[questionSourceType.value]
    filteredQuestionList.value = getFilteredQuestions()
  } else {
    // 获取题目列表
    fetchQuestions()
  }
}

// 显示编辑笔记对话框
const editNote = (note) => {
  noteDialog.value.isEdit = true
  
  // 获取当前题目是否为错题或收藏
  const isWrong = wrongQuestions.value.some(item => item.questionId === note.questionId)
  const isFavorite = favoriteQuestions.value.some(item => item.question_id === note.questionId)
  
  // 根据题目状态设置来源
  if (isWrong) {
    questionSourceType.value = 'wrong'
  } else if (isFavorite) {
    questionSourceType.value = 'favorite'
  } else {
    questionSourceType.value = 'wrong' // 如果既不是错题也不是收藏，默认为错题
  }
  
  noteForm.value = {
    noteId: note.noteId,
    questionId: note.questionId,
    content: note.content
  }
  
  noteDialog.value.visible = true
  
  // 如果已经加载过该类型的题目，直接使用缓存
  if (loadedQuestions.value[questionSourceType.value].length > 0) {
    questions.value = loadedQuestions.value[questionSourceType.value]
    filteredQuestionList.value = getFilteredQuestions()
  } else {
    // 获取对应来源的题目
    fetchQuestions()
  }
}

// 显示分享笔记对话框
const shareNote = (note) => {
  shareForm.value = {
    noteId: note.noteId,
    targetUserId: null
  }
  shareDialog.value.visible = true
}

// 提交笔记（添加/编辑）
const handleNoteSubmit = async () => {
  try {
    if (!noteForm.value.questionId) {
      ElMessage.warning('请选择题目')
      return
    }
    
    if (!noteForm.value.content.trim()) {
      ElMessage.warning('请输入笔记内容')
      return
    }

    if (noteDialog.value.isEdit) {
      // 编辑笔记
      const response = await axios.put(`http://localhost:8080/api/notes/update/${noteForm.value.noteId}`, {
        content: noteForm.value.content,
        userId: userStore.getUserInfo.userId
      })
      if (response.data.code === 200) {
        ElMessage.success('笔记更新成功')
        noteDialog.value.visible = false
        fetchNotes() // 刷新笔记列表
      } else {
        ElMessage.error(response.data.message || '笔记更新失败')
      }
    } else {
      // 添加笔记
      const response = await axios.post('http://localhost:8080/api/notes/createNote', {
        userId: userStore.getUserInfo.userId,
        questionId: noteForm.value.questionId,
        content: noteForm.value.content
      })
      if (response.data.code === 200) {
        ElMessage.success('笔记添加成功')
        noteDialog.value.visible = false
        fetchNotes() // 刷新笔记列表
      } else {
        ElMessage.error(response.data.message || '笔记添加失败')
      }
    }
  } catch (error) {
    console.error('保存笔记失败:', error)
    ElMessage.error('保存笔记失败，请稍后重试')
  }
}

// 提交分享
const handleShareSubmit = async () => {
  try {
    if (!shareForm.value.targetUserId) {
      ElMessage.warning('请选择要分享的用户')
      return
    }

    // 1. 先分享笔记
    const shareResponse = await axios.post(`http://localhost:8080/api/notes/${shareForm.value.noteId}/share`, null, {
      params: {
        senderId: userStore.getUserInfo.userId,
        receiverId: shareForm.value.targetUserId
      }
    })
    
    if (shareResponse.data.code === 200) {
      // 2. 发送消息通知
      const messageResponse = await axios.post(`http://localhost:8080/api/messages/share-note`, null, {
        params: {
          senderId: userStore.getUserInfo.userId,
          receiverId: shareForm.value.targetUserId,
          noteId: shareForm.value.noteId
        }
      })

      if (messageResponse.data.code === 200) {
        ElMessage.success('笔记分享成功')
        shareDialog.value.visible = false
      } else {
        ElMessage.error(messageResponse.data.message || '发送消息通知失败')
      }
    } else {
      ElMessage.error(shareResponse.data.message || '笔记分享失败')
    }
  } catch (error) {
    console.error('分享笔记失败:', error)
    console.error('错误详情:', {
      message: error.message,
      response: error.response?.data,
      status: error.response?.status,
      stack: error.response?.data?.trace
    })
    ElMessage.error('分享笔记失败，请稍后重试')
  }
}

// 获取用户列表
const fetchUsers = async () => {
  try {
    const response = await axios.get('http://localhost:8080/user/user_findall')
    users.value = response.data || []
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  }
}

// 删除笔记
const deleteNote = async (note) => {
  try {
    const response = await axios.delete(`http://localhost:8080/api/notes/delete/${note.noteId}`, {
      params: {
        userId: userStore.getUserInfo.userId
      }
    })
    
    if (response.data.code === 200) {
      ElMessage.success('笔记删除成功')
      fetchNotes() // 刷新笔记列表
    } else {
      ElMessage.error(response.data.message || '笔记删除失败')
    }
  } catch (error) {
    console.error('删除笔记失败:', error)
    ElMessage.error(error.response?.data?.message || '删除笔记失败，请稍后重试')
  }
}

// 组件卸载时清理图表实例
onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  window.removeEventListener('resize', () => {
    chartInstance && chartInstance.resize()
  })
})

// 获取所有课程进度
const fetchAllCourseProgress = async () => {
  const courseIds = [1, 2, 3, 4]
  const user = userStore.getUserInfo || userInfo.value
  const uid = user?.userId || userId.value

  const progresses = []
  for (const courseId of courseIds) {
    try {
      const { data } = await axios.get('/userPractices/point-progress', {
        params: { userId: uid, courseId }
      })
      if (data && typeof data.progress === 'number') {
        progresses.push(Math.round(data.progress))
      } else if (data && data.practicedCount !== undefined && data.totalCount) {
        progresses.push(Math.round((data.practicedCount / data.totalCount) * 100))
      } else {
        progresses.push(0)
      }
    } catch (e) {
      progresses.push(0)
    }
  }
  courseProgressList.value = progresses
}

// 计算平均进度
const averageProgress = computed(() => {
  if (!courseProgressList.value.length) return 0
  const sum = courseProgressList.value.reduce((a, b) => a + b, 0)
  return Math.round(sum / courseProgressList.value.length)
})

// 检查是否为错题
const isWrongQuestion = (questionId) => {
  return wrongQuestions.value.some(item => item.questionId === questionId)
}

// 检查是否为收藏题目
const isFavoriteQuestion = (questionId) => {
  return favoriteQuestions.value.some(item => item.question_id === questionId)
}

// 初始化数据
onMounted(async () => {
  try {
    // 等待用户信息加载完成
    if (!userStore.getUserInfo?.userId) {
      console.log('等待用户信息加载...')
      await new Promise(resolve => {
        const unwatch = watch(() => userStore.getUserInfo?.userId, (newVal) => {
          if (newVal) {
            unwatch()
            resolve(true)
          }
        })
      })
    }
    await Promise.all([
      fetchOverallProgress(),
      fetchKnowledgePoints(),
      initStudyTimeChart(),
      fetchNotes(),
      fetchQuestions(),
      fetchUsers(),
      fetchAllCourseProgress()
    ])
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('加载数据失败,请刷新页面重试')
  }
})

</script>

<style scoped>
.progress-container {
  padding: 20px; /* 恢复水平内边距 */
  max-width: 1200px; /* 恢复最大宽度 */
  margin: 0 auto; /* 水平居中 */
  margin-top: 0 !important; /* 保留外部容器与顶部菜单衔接 */
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 恢复 ElCard 默认的 body 内边距 */
:deep(.el-card__body) {
  padding: 20px !important; /* 恢复 ElCard 默认的内边距 */
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 0 24px; /* 恢复水平内边距 */
}

.page-header h2 {
  color: #4a6fa5;
  font-size: 1.5rem;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 16px;
}

.filter-select {
  width: 120px;
}

.section-wrapper {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(20px);
  border-radius: 12px;
  border: 1px solid rgba(107, 155, 210, 0.1);
  box-shadow: 0 8px 32px rgba(107, 155, 210, 0.1);
  padding: 0; /* 移除 padding */
}

.progress-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24px;
  padding: 20px; /* 恢复 padding */
}

.progress-card {
  background: none;
  border: none;
  box-shadow: none;
  /* 移除 padding: 0; 让卡片恢复默认的 body padding */
  transition: none;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  box-shadow: 0 8px 32px rgba(107, 155, 210, 0.1);
  padding: 20px; /* 恢复 padding */
}

.card-header h3 {
  color: #4a6fa5;
  font-size: 1.1rem;
  margin: 0;
}

.overall-progress {
  grid-column: span 2;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(20px);
  border-radius: 12px;
  border: 1px solid rgba(107, 155, 210, 0.1);
  box-shadow: 0 8px 32px rgba(107, 155, 210, 0.1);
  padding: 20px; /* 恢复 padding */
}

.progress-circle {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}

.progress-stats {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-top: 20px;
}

.stat-item {
  text-align: center;
}

.stat-item .label {
  display: block;
  color: #6b8bb0;
  font-size: 0.9rem;
  margin-bottom: 8px;
}

.stat-item .value {
  color: #4a6fa5;
  font-size: 1.5rem;
  font-weight: 600;
}

.chart-card {
  grid-column: span 2;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(20px);
  border-radius: 12px;
  border: 1px solid rgba(107, 155, 210, 0.1);
  box-shadow: 0 8px 32px rgba(107, 155, 210, 0.1);
  padding: 20px; /* 恢复 padding */
}

.chart-container {
  height: 300px;
  width: 100%;
}

.knowledge-card {
  grid-column: span 2;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(20px);
  border-radius: 12px;
  border: 1px solid rgba(107, 155, 210, 0.1);
  box-shadow: 0 8px 32px rgba(107, 155, 210, 0.1);
  padding: 20px; /* 恢复 padding */
}

.knowledge-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.knowledge-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.knowledge-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.knowledge-info .name {
  color: #4a6fa5;
  font-weight: 500;
}

.knowledge-info .progress-text {
  color: #6b8bb0;
  font-size: 0.9rem;
}

.notes-card {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 20px; /* 恢复 padding */
}

.notes-list {
  /* 移除 padding: 0; 让列表恢复默认内边距 */
  margin-bottom: 0;
  background: none;
  border-radius: 0;
}

.note-item {
  padding: 15px;
  margin-bottom: 15px;
  background: rgba(107, 155, 210, 0.05);
  border-radius: 8px;
}

.note-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.note-title-container {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.note-tags {
  display: flex;
  gap: 5px;
}

.note-content {
  color: #4a6fa5;
  margin: 10px 0;
}

.note-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #6b8bb0;
  font-size: 12px;
}

.note-actions {
  display: flex;
  gap: 8px;
}

.delete-btn {
  color: #F56C6C;
}

.delete-btn:hover {
  color: #f78989;
}

.progress-explanation {
  font-size: 12px;
  color: #6b8bb0;
  margin-top: 4px;
  text-align: right;
}

.calculation-explanation {
  margin-top: 20px;
}

.explanation-content {
  font-size: 12px;
}

.explanation-content p {
  margin: 5px 0;
}

.explanation-content ul {
  margin: 5px 0;
  padding-left: 20px;
}

.explanation-content li {
  margin: 3px 0;
}

@media (max-width: 1200px) {
  .progress-grid {
    grid-template-columns: 1fr;
  }

  .overall-progress,
  .chart-card,
  .knowledge-card {
    grid-column: span 1;
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
    padding: 0 16px;
  }

  .header-actions {
    flex-direction: column;
  }

  .filter-select {
    width: 100%;
  }

  .section-wrapper {
    padding: 12px; /* 恢复 padding */
  }
  
  .overall-progress,
  .chart-card,
  .knowledge-card {
    padding: 16px; /* 恢复 padding */
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-form-item__label) {
  color: #4a6fa5;
}

:deep(.el-input__wrapper) {
  box-shadow: 0 2px 12px rgba(107, 155, 210, 0.1);
}

:deep(.el-textarea__inner) {
  box-shadow: 0 2px 12px rgba(107, 155, 210, 0.1);
}

.question-option {
  padding: 4px 0;
}

.question-content {
  font-size: 14px;
  color: #4a6fa5;
  margin-bottom: 4px;
  white-space: normal;
  word-break: break-all;
}

.question-info {
  display: flex;
  gap: 8px;
}

:deep(.el-select-dropdown__item) {
  height: auto;
  padding: 8px 12px;
}

:deep(.el-select-dropdown__item.selected) {
  background-color: rgba(107, 155, 210, 0.1);
}
</style>
